<template>
  <div class="cart-modal" v-if="isOpen" @click="closeModal">
    <div class="cart-content" @click.stop>
      <div class="cart-header">
        <h3>购物车</h3>
        <button class="close-btn" @click="closeModal">×</button>
      </div>
      
      <div class="cart-body">
        <!-- 空购物车状态 -->
        <div v-if="cartItems.length === 0" class="empty-cart">
          <p>购物车为空</p>
        </div>
        
        <!-- 购物车有商品时 -->
        <div v-else>
          <div class="cart-items">
            <div v-for="item in cartItems" :key="item.id" class="cart-item">
              <img :src="item.image" :alt="item.name" class="item-image" />
              <div class="item-info">
                <h4>{{ item.name }}</h4>
                <p class="item-price">¥{{ item.price }}</p>
              </div>
              <!-- 数量控制（防止数量为负） -->
              <div class="quantity-controls">
                <button 
                  @click="updateQuantity(item.id, item.quantity - 1)"
                  :disabled="item.quantity <= 1"
                >-</button>
                <span class="quantity">{{ item.quantity }}</span>
                <button @click="updateQuantity(item.id, item.quantity + 1)">+</button>
              </div>
              <!-- 商品小计 -->
              <div class="item-total">¥{{ (item.price * item.quantity).toFixed(2) }}</div>
              <!-- 删除按钮 -->
              <button class="remove-btn" @click="removeFromCart(item.id)">删除</button>
            </div>
          </div>
          
          <div class="cart-footer">
            <div class="total-section">
              <p>总计: ¥{{ cartTotal.toFixed(2) }}</p>
              <p>用户余额: ¥{{ userBalance.toFixed(2) }}</p>
            </div>
            <div class="action-buttons">
              <button @click="handleRecharge" class="recharge-btn">充值</button>
              <button 
                @click="handleCheckout" 
                class="checkout-btn" 
                :disabled="!canAfford(cartTotal)"
              >
                {{ canAfford(cartTotal) ? '立即购买' : '余额不足' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 1. 导入必要依赖（仅保留使用到的）
import { computed } from 'vue'  // 移除未使用的 ref
import { useCartStore } from '../stores/cart'

// 2. 定义Props（明确类型约束，与父组件传参匹配）
const props = defineProps({
  isOpen: {
    type: Boolean,
    required: true,  // 标记为必传，避免父组件漏传
    default: false
  }
})

// 3. 定义Emits（明确事件类型，与父组件通信匹配）
const emit = defineEmits(['close', 'recharge', 'checkout'])

// 4. 初始化Store
const cartStore = useCartStore()

// 5. 计算属性（依赖Store状态，避免直接操作原始数据）
const cartItems = computed(() => cartStore.items || [])  // 兜底空数组，防止报错
const cartTotal = computed(() => cartStore.cartTotal || 0)
const userBalance = computed(() => cartStore.userBalance || 0)
// 修复：canAfford 改为函数（原代码中 computed 无法直接接收参数）
const canAfford = (total) => {
  return userBalance.value >= total
}

// 6. 事件处理函数（与Emits/Store方法对应）
const closeModal = () => {
  emit('close')  // 触发关闭弹窗事件
}

const updateQuantity = (productId, quantity) => {
  // 确保数量不小于1（避免负数）
  if (quantity < 1) return
  cartStore.updateQuantity(productId, quantity)
}

const removeFromCart = (productId) => {
  // 可选：添加删除确认
  if (confirm('确定要删除该商品吗？')) {
    cartStore.removeFromCart(productId)
  }
}

const handleRecharge = () => {
  emit('recharge')  // 触发充值事件
}

const handleCheckout = () => {
  const result = cartStore.purchase()
  if (result.success) {
    alert('购买成功！')
    emit('checkout', result.order)  // 触发结算事件，传递订单信息
    closeModal()  // 购买成功后关闭弹窗
  } else {
    alert(result.message || '购买失败，请稍后再试')  // 兜底错误提示
  }
}
</script>

<style scoped>
.cart-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: flex-end;
  z-index: 1000;
  backdrop-filter: blur(2px);  /* 增加背景模糊，提升视觉体验 */
}

.cart-content {
  background: white;
  width: 400px;
  height: 100%;
  display: flex;
  flex-direction: column;
  animation: slideIn 0.3s ease-out;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.1);  /* 增加阴影，区分层级 */
}

@keyframes slideIn {
  from { transform: translateX(100%); }
  to { transform: translateX(0); }
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.cart-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #e74c3c;  /*  hover时变色，提升交互反馈 */
}

.cart-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.empty-cart {
  text-align: center;
  color: #666;
  margin-top: 50px;
  font-size: 14px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 15px 0;  /* 增加内边距，提升间距 */
  border-bottom: 1px solid #eee;
  gap: 12px;  /* 统一元素间距 */
}

.item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #f5f5f5;  /* 增加边框，避免图片模糊 */
}

.item-info {
  flex: 1;
}

.item-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  white-space: nowrap;  /* 避免商品名换行 */
  overflow: hidden;
  text-overflow: ellipsis;  /* 超长商品名显示省略号 */
}

.item-price {
  color: #e74c3c;
  font-weight: bold;
  margin: 0;
  font-size: 13px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-controls button {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.2s;
}

.quantity-controls button:disabled {
  background: #f5f5f5;
  color: #ccc;
  cursor: not-allowed;
}

.quantity-controls button:hover:not(:disabled) {
  background: #f5f5f5;
}

.quantity {
  min-width: 30px;
  text-align: center;
  font-size: 14px;
}

.item-total {
  font-weight: bold;
  color: #e74c3c;
  font-size: 14px;
  min-width: 80px;
  text-align: right;
}

.remove-btn {
  background: #e74c3c;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s;
}

.remove-btn:hover {
  background: #c0392b;  /* 加深颜色，提升交互反馈 */
}

.cart-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  background: #fafafa;  /* 增加背景色，区分内容区 */
}

.total-section p {
  margin: 8px 0;
  font-size: 16px;
  color: #333;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 15px;
}

.recharge-btn {
  flex: 1;
  background: #3498db;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.recharge-btn:hover {
  background: #2980b9;
}

.checkout-btn {
  flex: 2;
  background: #27ae60;
  color: white;
  border: none;
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.checkout-btn:disabled {
  background: #95a5a6;
  cursor: not-allowed;
}

.checkout-btn:hover:not(:disabled) {
  background: #219653;
}

/* 适配小屏幕 */
@media (max-width: 480px) {
  .cart-content {
    width: 100%;
  }
  
  .item-total {
    min-width: 60px;
  }
}
</style>